package mealhistory;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import java.util.List;

public class MealExpandableAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<MealGroup> mealGroups;

    public MealExpandableAdapter(Context context, List<MealGroup> mealGroups) {
        this.context = context;
        this.mealGroups = mealGroups;
    }

    @Override
    public int getGroupCount() {
        return mealGroups.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return mealGroups.get(groupPosition).getMeals().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return mealGroups.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return mealGroups.get(groupPosition).getMeals().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int childPosition, int groupPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false);
        }
        TextView text = convertView.findViewById(android.R.id.text1);
        MealGroup group = (MealGroup) getGroup(groupPosition);
        text.setText(group.getDate() + " - " + group.getType());
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(android.R.layout.simple_list_item_2, parent, false);
        }
        TextView text1 = convertView.findViewById(android.R.id.text1);
        TextView text2 = convertView.findViewById(android.R.id.text2);
        Mealitem item = (Mealitem) getChild(groupPosition, childPosition);
        text1.setText(item.getFoodname());
        text2.setText("Weight: " + item.getWeight() + ", Calories: " + item.getConsumption());
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}
